package Semantic;

import java.io.FileOutputStream;
import java.io.PrintStream;

public class CodeGenerator {
	
	private StringBuilder variables;
	private StringBuilder instructions;
	
	private String output;
	private String label = "";
	
	public CodeGenerator(String output) {
		variables = new StringBuilder();
		instructions = new StringBuilder();
		this.output = output;
	}
	
	public void writeVariable(String operator, String operand) {
		variables.append(label + "\t" + operator + "\t" + operand + "\n");
		label = "";
	}
		
	public void writeInstruction (String operator, String operand){
		instructions.append(label + "\t" + operator + "\t" + operand + "\n");
		label = "";
	}
	
	public void generateCodeFile()
    {
		FileOutputStream out; // declare a file output object
        PrintStream p; // declare a print stream object
        
        try {
            // Create a new file output stream
            out = new FileOutputStream(output);

            // Connect print stream to the output stream
            p = new PrintStream(out);

            p.print(variables.toString() + instructions.toString());

            p.close();
	    }
	    catch (Exception e)
	    {
	            System.err.println ("Error writing to file");
	    } 
    }
	
	public void setLabel(String label) {
		if (this.label.equals(""))
			this.label = label;
		else {
			writeInstruction("OS", "/0000");
			this.label = label;
		}
			
	}	
}
